package init

import (
	"fmt"
	"github.com/spf13/viper"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"one_exam/global"
	"time"
)

func init() {
	InitConfig()
	InitMySQLConfig()
}

// 初始化配置文件
func InitConfig() {
	viper.SetConfigFile("D:\\goWork\\homework\\one_exam\\dev.yaml")
	viper.ReadInConfig()
	viper.Unmarshal(&global.Global)
	fmt.Println(global.Global)
}

var err error

// 初始化MySQL连接
func InitMySQLConfig() {

	config := global.Global.Mysql
	dsn := fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8&parseTime=True", config.User, config.Password, config.Host, config.Port, config.Database)
	global.DB, err = gorm.Open(mysql.Open(dsn))
	if err != nil {
		panic(err)
	}
	fmt.Println("MySQL连接成功")
	sqlDB, _ := global.DB.DB()
	// SetMaxIdleConns sets the maximum number of connections in the idle connection pool.
	sqlDB.SetMaxIdleConns(10)
	// SetMaxOpenConns sets the maximum number of open connections to the database.
	sqlDB.SetMaxOpenConns(100)
	// SetConnMaxLifetime sets the maximum amount of time a connection may be reused.
	sqlDB.SetConnMaxLifetime(time.Hour)
}
